﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class UserRepository : BaseRepository<TUser>, IUserRepository
    {
        public UserRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }


        /// <summary>
        /// 16位MD5加密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string MD5Encrypt16(string password)
        {
            var md5 = MD5.Create();
            string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password)), 4, 8);
            t2 = t2.Replace("-", string.Empty);
            return t2;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddUser(UserRoleDto m)
        {
            //使用事务的原子性
            using (var tran=Context.Database.BeginTransaction())
            {
                try
                {
                    var obj = Context.TUsers.AsNoTracking().FirstOrDefault(x => x.UserName == m.UserName);
                    if(obj!=null)
                    {
                        return false;
                    }
                    //添加用户
                    TUser user = new TUser();
                    user = Mapper.Map<TUser>(m);
                    user.Pwd = MD5Encrypt16(user.Pwd);
                    user.CreateUserId = m.NowUserId;
                    user.CreateUserName = m.RealName;
                    user.CreateDate = DateTime.Now;
                    user.ModifyDate = DateTime.Now;
                    user.ModifyUserName = m.RealName;
                    user.ModifyUserId = m.NowUserId;
                    Context.TUsers.Add(user);
                    Context.SaveChanges();
                    //循环遍历角色
                    foreach (var item in m.RoleIds.Split(','))
                    {
                        TUserRole ur = new TUserRole();
                        ur.UserId = user.Id;
                        ur.RoleId = Convert.ToInt32(item);
                        Context.Add(ur);
                        Context.SaveChanges();
                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    tran.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelUser(int uid)
        {
            try
            {
                var uobj = Context.TUsers.Find(uid);
                if (uobj != null)
                {
                    Context.Remove(uobj);
                    var urlist = Context.TUserRoles.AsNoTracking().Where(x => x.UserId == uid);
                    Context.RemoveRange(urlist.ToList());
                }
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <param name="ulist"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelUsers(List<TUser> ulist)
        {
            if(ulist!=null)
            {
                Context.TUsers.RemoveRange(ulist);
                foreach (var item in ulist)
                {
                    var urlist = Context.TUserRoles.AsNoTracking().Where(x => x.UserId == item.Id);
                    
                    Context.RemoveRange(urlist.ToList());
                }
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 判断登录
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TUser GetLogin(LoginDto m)
        {
            try
            {
                var obj = Context.TUsers.FirstOrDefault(x => x.UserName == m.User_Name);
                if (obj != null)
                {
                    //MD5加密
                    m.User_Password = MD5Encrypt16(m.User_Password);
                    if (obj.Pwd == m.User_Password && obj.Status==1)
                    {                
                        return obj;
                    }
                }
                return null;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 判断登录
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TUser GetLoginPDA(LoginPDADTO pDADTO)
        {
            try
            {
                var obj = Context.TUsers.FirstOrDefault(x => x.UserName == pDADTO.LoginName);
                if (obj != null)
                {
                    //MD5加密
                    pDADTO.LoginPwd = MD5Encrypt16(pDADTO.LoginPwd);
                    if (obj.Pwd == pDADTO.LoginPwd && obj.Status == 1)
                    {
                        return obj;
                    }
                }
                return null;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 用户显示
        /// </summary>
        /// <param name="uname"></param>
        /// <param name="rid"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<UserDeptRoleListDto> GetUserList(string uname, int rid, int state,int pageIndex, int pageSize, out int totalCount)
        {
            try
            {               
                //用户
                var ulist = Context.TUsers.AsNoTracking().AsQueryable();
                if (!string.IsNullOrEmpty(uname))
                {
                    ulist = ulist.Where(x => x.UserName.Contains(uname));
                }

                if (state != 3)
                {
                    ulist = ulist.Where(x => x.Status == state);
                }
                //用户角色关系
                var urlist = Context.TUserRoles.AsNoTracking().AsQueryable();

                if (rid != 0)
                {
                    urlist = urlist.Where(x => x.RoleId == rid);
                }
                //角色
                var rlist=Context.TRoles.AsNoTracking().AsQueryable();
                //部门
                var dlist=Context.TDepartments.AsNoTracking().AsQueryable();
                var list = (from u in ulist                           
                            join ur in urlist
                            on u.Id equals ur.UserId                          
                            select new UserDeptRoleListDto { 
                            Id= u.Id,
                            UserName = u.UserName,
                            DepartmentId = u.DepartmentId,
                            MobilePhone = u.MobilePhone,
                            CreateDate = u.CreateDate
                            }).Distinct();
                list = list.Select(x => new UserDeptRoleListDto
                {
                    Id = x.Id,
                    UserName= x.UserName,
                    DepartmentId = x.DepartmentId,
                    RoleName = GetUserRoleName(urlist.ToList(), rlist.ToList(), x.Id).TrimEnd(','),
                    DepartmentName= dlist.AsNoTracking().FirstOrDefault(d=>d.Id==x.DepartmentId).DepartmentName??"",
                    MobilePhone = x.MobilePhone,
                    CreateDate = x.CreateDate
                });             
                totalCount = list.Count();
                return list.OrderBy(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }
        public static string GetUserRoleName(List<TUserRole> rulist,List<TRole> rlist,int uid)
        {
            string rname = "";
            var rid = rulist.Where(x => x.UserId == uid).Select(x => x.RoleId);
            foreach (var item in rid)
            {
               rname += rlist.FirstOrDefault(x => x.Id == item).RoleName + ",";
            }
            return rname;
        }
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdUser(UserRoleDto m)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {          
                    var list = Context.TUsers.AsNoTracking().FirstOrDefault(x => x.Id != m.Id && x.UserName == m.UserName);

                    if (list!= null)
                    {
                        return false;
                    }
                    //更新要修改的信息
                    TUser user = new TUser();
                    user = Mapper.Map<TUser>(m);
                    user.Pwd = MD5Encrypt16(user.Pwd);
                    user.ModifyUserId = m.NowUserId;
                    user.ModifyUserName = m.NowUserRealName;
                    user.ModifyDate = DateTime.Now;
                    Context.Update(user);

                    //获取当前用户的所有角色
                    var urlist = Context.TUserRoles.Where(x => x.UserId == user.Id);
                    if (urlist.Any())
                    {
                        //删除当前用户的所有角色
                        Context.RemoveRange(urlist);                      
                    }
                    foreach (var item in m.RoleIds.Split(','))
                    {
                        TUserRole userRole = new TUserRole();
                        userRole.UserId = m.Id;
                        userRole.RoleId = Convert.ToInt32(item);
                        Context.TUserRoles.Add(userRole);
                    }
                    tran.Commit();
                    return Context.SaveChanges() > 0;
                }
                catch (Exception)
                {
                    //事务回滚
                    tran.Rollback();
                    throw;
                }
            }
              

        }

        /// <summary>
        /// 修改用户状态
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool UpdUserStatus(UpdStatusDto m)
        {
            var uobj = Context.TUsers.Find(m.Id);
            if(uobj!=null)
            {
                int? status = uobj.Status;
                if(status==0)
                { 
                    uobj.Status = 1;
                }
                else
                uobj.Status = 0;

                uobj.ModifyUserId = m.NowUserId;
                uobj.ModifyUserName = m.NowUserRealName;
                uobj.ModifyDate= DateTime.Now;
                Context.TUsers.Update(uobj);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 根据主键获取用户Id
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public UserRoleDto URById(int uid)
        {
            try
            {
                var uobj = Context.TUsers.Find(uid);
                if (uobj != null)
                {
                    UserRoleDto urdto = new UserRoleDto();
                    urdto = Mapper.Map<UserRoleDto>(uobj);
                    var ur = Context.TUserRoles.Where(x => x.UserId == uid);
                    if (ur.Count() > 0)
                    {
                        foreach (var item in ur)
                        {
                            urdto.RoleIds += item.RoleId + ",";
                        }
                        urdto.RoleIds = urdto.RoleIds.TrimEnd(',');
                    }
                    return urdto;
                }
                return null;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UserModifyPwd(ModifyPwdDto m)
        {
            try
            {
                var uobj = Context.TUsers.Find(m.NowUserId);

                if (uobj != null)
                {
                    m.NowPwd = MD5Encrypt16(m.NowPwd);
                    if (uobj.Pwd == m.NowPwd)
                    {
                        m.NewPwd = MD5Encrypt16(m.NewPwd);
                        uobj.Pwd = m.NewPwd;
                        uobj.ModifyDate = DateTime.Now;
                        Context.TUsers.Update(uobj);
                    }
                    else
                    {
                        return false;
                    }
                }
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }

       /// <summary>
       /// 重置密码
       /// </summary>
       /// <param name="m"></param>
       /// <returns></returns>
        public bool UserResetPwd(ResetPwdDto m)
        {
            try
            {
                var obj = Context.TUsers.Find(m.uid);
                if (obj != null)
                {
                    obj.ModifyUserId = m.NowUserId;
                    obj.ModifyUserName = m.NowUserRealName;
                    obj.ModifyDate = DateTime.Now;
                    obj.Pwd = "8AD9902AECBA32E2";
                    Context.TUsers.Update(obj);
                }
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }
        public List<TUser> GetUserExcel()
        {
            try
            {
                var list = Context.TUsers.AsQueryable();  
                return list.ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddUserList(List<TUser> list)
        {
            Context.TUsers.AddRange(list);
            return Context.SaveChanges() > 0;
        }
    }
}
